package com.situ.studentmanagement.controller;

import com.alibaba.druid.support.logging.Log;
import com.situ.studentmanagement.Constants;
import com.situ.studentmanagement.OneDayCheckInfo;
import com.situ.studentmanagement.Utils;
import com.situ.studentmanagement.dao.AdminMapper;
import com.situ.studentmanagement.dao.CheckInfoMapper;
import com.situ.studentmanagement.dao.ClassMapper;
import com.situ.studentmanagement.dao.StudentMapper;
import com.situ.studentmanagement.model.Admin;
import com.situ.studentmanagement.model.CheckLog;
import com.situ.studentmanagement.model.ClassRoom;
import com.situ.studentmanagement.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by baba on 2016/7/8.
 */
@Controller
@RequestMapping("/Saccount")
public class StudentAccountController {
    private int modifyID;
    @Autowired
    private StudentMapper studentMapper;

    private String errMsg;
    @Autowired
    private ClassMapper classMapper;
    @Autowired
    private CheckInfoMapper checkLogMappler;

    private int CheckinId;

    //在将要跳转到学生注册页面时，将班级信息传递过去，供选择
    @RequestMapping(value = "/sign_up_student", method = RequestMethod.GET)
    public String signUp(HttpSession session, Model model) throws UnsupportedEncodingException {


        List<ClassRoom> classArray = classMapper.getAllClassRoom();

        model.addAttribute("classArray", classArray);

        return "sign_up_student";
    }


    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(HttpSession session, Model model,
                           @RequestParam("name") String name,
                           @RequestParam("password") String password,
                           @RequestParam("phone") String phone,
                           @RequestParam("email") String email,
                           @RequestParam("sex") String sex,
                           @RequestParam("address") String address,
                           @RequestParam("class_name") String class_name
    ) throws UnsupportedEncodingException {

        Boolean StudentSex;
        if (name.equals("")) {
            name = null;
        }
        if (password.equals("")) {
            password = null;
        }
        if (sex.equals("")) {
            sex = null;
        }

        if (name == null || password == null || sex == null) {
            errMsg = "用户名/密码/性别 不能为空！！！";
            //放到model中的数据可以在jsp中直接使用
            model.addAttribute("errMsg", errMsg);
            List<ClassRoom> classArray = classMapper.getAllClassRoom();

            model.addAttribute("classArray", classArray);

//                    return "redirect:student/sign_up_student";
            return "sign_up_student";
        } else {

            if (sex.equals("man")) {

                StudentSex = false;
            } else {
                StudentSex = true;
            }

            int class_id = Integer.parseInt(class_name);

            Student student = new Student(0, name, password, phone, email, StudentSex, address, class_id, null);
            studentMapper.StudentRegister(student);
            //注册成功，回到登录页面
            session.setAttribute("value_name", name);
            String url = "redirect:/";
            return url;
        }


    }

    //跳转到添加学生页面
    @RequestMapping(value = "/addStudent", method = RequestMethod.GET)
    public String addStudent(Model model) {
        List<ClassRoom> classArray = classMapper.getAllClassRoom();

        model.addAttribute("classArray", classArray);

        return "add_student";
    }

    @RequestMapping(value = "/register2")
    public String register2(HttpSession session, Model model,
                            @RequestParam("name") String name,
                            @RequestParam("password") String password,
                            @RequestParam("phone") String phone,
                            @RequestParam("email") String email,
                            @RequestParam("sex") String sex,
                            @RequestParam("address") String address,
                            @RequestParam("class_name") String class_name
    ) throws UnsupportedEncodingException {

        Boolean StudentSex;
        if (name.equals("")) {
            name = null;
        }
        if (password.equals("")) {
            password = null;
        }
        if (sex.equals("")) {
            password = null;
        }

        if (name == null || password == null || sex == null) {
            errMsg = "用户名/密码/性别 不能为空！！！";
            //放到model中的数据可以在jsp中直接使用
            model.addAttribute("errMsg", errMsg);
            List<ClassRoom> classArray = classMapper.getAllClassRoom();

            model.addAttribute("classArray", classArray);
//                    return "redirect:student/sign_up_student";
            return "add_student";
        } else {

            if (sex.equals("man")) {

                StudentSex = false;
            } else {
                StudentSex = true;
            }

            int class_id = Integer.parseInt(class_name);

            Student student = new Student(0, name, password, phone, email, StudentSex, address, class_id, null);
            studentMapper.StudentRegister(student);


            List<Student> students = studentMapper.getAllStudent();
            model.addAttribute("students", students);
            return "student_man";
        }


    }

    @RequestMapping(value = "/student_man")
    public String classMan(Model model) {
        List<Student> students = studentMapper.getAllStudent();
        model.addAttribute("students", students);
        return "student_man";
    }

    @RequestMapping(value = "/quxiao")
    public String quxiao() {
        return "index";
    }

    //退出登录
    @RequestMapping(value = "/tuichu", method = RequestMethod.GET)
    public String tuichu(Model model, HttpSession session) {
        session.setAttribute(Constants.STUDENT_LOGIN_ATTR_ID, null);


        session.setAttribute(Constants.ADMIN_LOGIN_ATTR_ID, null);

        return "redirect:/";
    }
    //跳转到修改学生信息页面

    @RequestMapping(value = "/modifyStudent")
    public String modifyStudent(Model model,
                                @RequestParam("modify_id") int modify_id) {
        List<ClassRoom> classArray = classMapper.getAllClassRoom();

        model.addAttribute("classArray", classArray);
        modifyID = modify_id;
        Student student = studentMapper.getStudentById(modify_id);
        model.addAttribute("student", student);
        return "modify_student";
    }

    //修改学生信息
    @RequestMapping(value = "/modifystu")
    public String modifystu(Model model,
                            @RequestParam("name") String name,
                            @RequestParam("password") String password,
                            @RequestParam("phone") String phone,
                            @RequestParam("email") String email,
                            @RequestParam("sex") String sex,
                            @RequestParam("address") String address,
                            @RequestParam("class_name") int class_id) {
        int sexx;
        if (sex.equals("man")) {
            sexx = 1;
        } else {
            sexx = 0;
        }

        studentMapper.setStudentById(modifyID, name, password, phone, email, sexx, address, class_id);
        List<Student> students = studentMapper.getAllStudent();
        model.addAttribute("students", students);
        return "student_man";
    }

    //导航到签到页面
    @RequestMapping(value = "/qiandao")
    public String qiandao() {
        return "qianDao";
    }


    //学生签到签到后传递打卡时间并回到 个人考勤信息页面
    @RequestMapping(value = "/checkin")
    public String checkin(HttpSession session, Model model) {
        //获取登录的学生的id
        int student_id = (int) session.getAttribute(Constants.STUDENT_LOGIN_ATTR_ID);

        //从数据库中查询，判断是否已经考勤，若是，则不再往数据库中插入
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        calendar.setTime(date);

        int nowDay = calendar.get(Calendar.DAY_OF_YEAR);
        List<CheckLog> checkLogs2 = checkLogMappler.getCheckinById(student_id);
        for (int i = 0; i < checkLogs2.size(); i++) {
            Date date2 = checkLogs2.get(i).getCheckInTime();
            calendar2.setTime(date2);
            int befDate = calendar2.get(Calendar.DAY_OF_YEAR);
            if (nowDay == befDate) {
                //获取考勤信息列表，默认显示当月信息
                String firstDayOfMonth = Utils.getFirstDayOfMonthString(new Date());
                String lastDayOfMonth = Utils.getLastDayOfMonthString(new Date());
                //获取考勤信息列表
                List<CheckLog> checkLogs = checkLogMappler.getCheckLogForOneMonth(
                        student_id, firstDayOfMonth, lastDayOfMonth);
                //从考勤信息列表产生OneDayCheckInfo列表
                List<OneDayCheckInfo> ret = new ArrayList();
                for (CheckLog cl : checkLogs) {
                    String curDay = Utils.getDateStringForDay(cl.getCheckInTime());
                    String checkInTime = Utils.getDateStringForTime(cl.getCheckInTime());
                    String checkOutTime = Utils.getDateStringForTime(cl.getCheckOutTime());
                    ret.add(new OneDayCheckInfo(curDay, checkInTime, checkOutTime));
                }
                model.addAttribute("check_list", ret);
                model.addAttribute("account_html", Constants.getStudentLoginAcccountHtml(studentMapper, session));
                return "check";

            }
        }
        String time = format.format(date);
        studentMapper.setLoginCheckinTime(student_id, time);
        CheckinId = checkLogMappler.getCheckinId(time);
        //获取考勤信息列表，默认显示当月信息
        String firstDayOfMonth2 = Utils.getFirstDayOfMonthString(new Date());
        String lastDayOfMonth2 = Utils.getLastDayOfMonthString(new Date());


        //获取考勤信息列表
        List<CheckLog> checkLogs = checkLogMappler.getCheckLogForOneMonth(
                student_id, firstDayOfMonth2, lastDayOfMonth2);
        if (checkLogs.isEmpty()) {
            model.addAttribute("check_list", checkLogs);
            model.addAttribute("account_html", Constants.getStudentLoginAcccountHtml(studentMapper, session));
            return "check";
        }

        //从考勤信息列表产生OneDayCheckInfo列表
        List<OneDayCheckInfo> ret = new ArrayList();
        for (CheckLog cl : checkLogs) {
            String curDay = Utils.getDateStringForDay(cl.getCheckInTime());
            String checkInTime = Utils.getDateStringForTime(cl.getCheckInTime());
            String checkOutTime = Utils.getDateStringForTime(cl.getCheckOutTime());
            ret.add(new OneDayCheckInfo(curDay, checkInTime, checkOutTime));
        }


        //通过model向前台传递数据
        model.addAttribute("check_list", ret);
        model.addAttribute("account_html", Constants.getStudentLoginAcccountHtml(studentMapper, session));

        return "check";
    }

    //学生签到签退后传递打卡时间并回到 个人考勤信息页面
    @RequestMapping(value = "/checkout")

    public String checkout(HttpSession session, Model model) {
        //获取登录的学生的id
        int student_id = (int) session.getAttribute(Constants.STUDENT_LOGIN_ATTR_ID);


        //从数据库中查询，判断是否已经签退，若是，则不再往数据库中写入（更改）
        Date checkoutTine = checkLogMappler.getCheckoutTimeById(CheckinId);
       if (checkoutTine != null) {
           //获取考勤信息列表，默认显示当月信息
           String firstDayOfMonth = Utils.getFirstDayOfMonthString(new Date());
           String lastDayOfMonth = Utils.getLastDayOfMonthString(new Date());
           //获取考勤信息列表
           List<CheckLog> checkLogs = checkLogMappler.getCheckLogForOneMonth(
                   student_id, firstDayOfMonth, lastDayOfMonth);
           //从考勤信息列表产生OneDayCheckInfo列表
           List<OneDayCheckInfo> ret = new ArrayList();
           for (CheckLog cl : checkLogs) {
               String curDay = Utils.getDateStringForDay(cl.getCheckInTime());
               String checkInTime = Utils.getDateStringForTime(cl.getCheckInTime());
               String checkOutTime = Utils.getDateStringForTime(cl.getCheckOutTime());
               ret.add(new OneDayCheckInfo(curDay, checkInTime, checkOutTime));
           }
           model.addAttribute("check_list", ret);
           model.addAttribute("account_html", Constants.getStudentLoginAcccountHtml(studentMapper, session));
           return "check";
       }


            Date date = new Date();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = format.format(date);
            this.studentMapper.setLoginCheckoutTime(student_id, CheckinId, time);

            //获取考勤信息列表，默认显示当月信息
            String firstDayOfMonth2 = Utils.getFirstDayOfMonthString(new Date());
            String lastDayOfMonth2 = Utils.getLastDayOfMonthString(new Date());


            //获取考勤信息列表
            List<CheckLog> checkLogs = checkLogMappler.getCheckLogForOneMonth(
                    student_id, firstDayOfMonth2, lastDayOfMonth2);

            if (checkLogs.isEmpty()) {
                model.addAttribute("check_list", checkLogs);
                model.addAttribute("account_html", Constants.getStudentLoginAcccountHtml(studentMapper, session));
                return "check";
            }

            //从考勤信息列表产生OneDayCheckInfo列表
            List<OneDayCheckInfo> ret = new ArrayList();
            for (CheckLog cl : checkLogs) {
                String curDay = Utils.getDateStringForDay(cl.getCheckInTime());
                String checkInTime = Utils.getDateStringForTime(cl.getCheckInTime());
                String checkOutTime = Utils.getDateStringForTime(cl.getCheckOutTime());
                ret.add(new OneDayCheckInfo(curDay, checkInTime, checkOutTime));
            }


            //通过model向前台传递数据
            model.addAttribute("check_list", ret);
            model.addAttribute("account_html", Constants.getStudentLoginAcccountHtml(studentMapper, session));
            return "check";


    }



}